package com.kimu.user_service_provider.service;

import java.util.Random;
import java.time.Duration;

import org.apache.dubbo.config.annotation.DubboService;
import org.redisson.api.RScoredSortedSet;
import org.redisson.api.RedissonClient;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kimu.user.entity.User;
import com.kimu.user.mapper.UserMapper;
import com.kimu.user.service.UserService;


@DubboService
public class UserServiceImpl implements UserService {
	
	private UserMapper userMapper;

	private RedissonClient redissonClient;

	public UserServiceImpl(UserMapper userMapper, RedissonClient redissionClient) {
		this.userMapper = userMapper;
		this.redissonClient = redissionClient;
	}

	@Override
	public User findUserById(Long id) {
		User user = userMapper.selectById(id);
		return user;
	}

	@Override
	public User findUserByUsername(String username) {
		User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
		return user;
	}

	/*
	 * 在添加一个用户后，将信息写入日志中
	 */
	@Override
	public int addUser(User user) {
		int row = userMapper.insert(user);
		return row;
	}

	@Override
	public int updateUser(User user) {
		int row = userMapper.updateById(user);
		return row;
	}

	@Override
	public int deleteUserById(Long id) {
		int row = userMapper.deleteById(id);
		return row;
	}

	/*
	 * 创建验证码，在注册之前需要先验证邮箱
	 */
	@Override
	public int createValidCode(String email) {
		// 首先判断邮箱对应的zset是否有3个元素，如果有直接返回0
		RScoredSortedSet<String> validCodeSet = redissonClient.getScoredSortedSet("validCode:" + email);
		if (validCodeSet.size() >= 3) {
			return 0;
		}
		// 元素个数没有到3，就向此集合中加入一个验证码
		// 生成6位随机验证码
		String validCode = String.format("%06d", new Random().nextInt(999999));
		System.out.println(validCode);
		// 将验证码加入zset，score使用当前时间戳
		validCodeSet.add(System.currentTimeMillis(), validCode);
		// 设置过期时间为10分钟
		validCodeSet.expire(Duration.ofMinutes(10));
		return 1;
	}

	@Override
	public int register(User user, String validCode) {
		// 首先判断验证码和邮箱对应的zset中的最近元素是否匹配
		String email = user.getEmail();
		RScoredSortedSet<String> validCodeSet = redissonClient.getScoredSortedSet("validCode:" + email);
		// 获取最新的验证码（score最大的元素）
		String latestValidCode = validCodeSet.last();
		System.out.println(latestValidCode);
		if (latestValidCode == null || !latestValidCode.equals(validCode)) {
			return 0;
		}
		// 验证成功，新增一个用户
		addUser(user);
		return 1;
	}

	/*
	 * 登录，判断用户名和密码是否匹配
	 * 登录成功后，将登录记录写入到日志中
	 */
	@Override
	public User login(User user) {
		String username = user.getUsername();
		User userFinded = findUserByUsername(username);
		if (userFinded == null) {
			return null;
		}
		String password = user.getPassword();
		if (password.equals(userFinded.getPassword())) {
			return userFinded;
		} else {
			return null;
		}
	}

}
